package com.emr.common;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class ChangeBean {
	
	/**
	 * 获取昨天日期
	 */
	public static String getYesterday() {
		Calendar c = Calendar.getInstance();
		c.add(Calendar.DATE, -1);
		Date d = new Date();
		d = c.getTime();
		SimpleDateFormat fm = new SimpleDateFormat("yyyy-MM-dd");
		return fm.format(d);
	}
	
	
	/**
	 * 获取项目路径
	 * @return
	 */
	public static String getProjectPath() {
		String projectPath = "";
		String tempPath = ChangeBean.class.getClassLoader().getResource("").getPath();
		if (tempPath.length() > 0) {
			tempPath = tempPath.substring(1, tempPath.length());
			if (tempPath.indexOf("\\") > -1) {
				tempPath = tempPath.replace("\\", "/");
			}
		}
		File file = new File(tempPath);
		if (file.exists()) {
			projectPath = file.getAbsolutePath();
			if (projectPath.indexOf("\\") > -1) {
				projectPath = projectPath.replace("\\", "/");
			}
		} else {
			projectPath = file.getPath();
			if (projectPath.indexOf("\\") > -1) {
				projectPath = projectPath.replace("\\", "/");
			}
			projectPath = "/" + projectPath;
		}
		try {
			projectPath = java.net.URLDecoder.decode(projectPath, "UTF-8");
			if (projectPath.indexOf("/WEB-INF") > -1) {
				projectPath = projectPath.substring(0, projectPath.indexOf("/WEB-INF"));
			}
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return projectPath;
	}
	
	/**
	 * 获取时间
	 * @return
	 */
	public static String getNowTime() {
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		java.util.Date now = new java.util.Date();
		String date = formatter.format(now);
		return date;
	}
	
	/**
	 * 获取当前时间
	 * @return
	 */
	public static Date getNowDate() {
		Date date = new Date();
		String time = getNowTime();
		date = stringToDate(time);
		return date;
	}
	
	/**
	 * string日期形转为date形
	 * @param sDate
	 * @return
	 */
	public static Date stringToDate(String sDate) {
		if ("".equals(clearNull(sDate))) { return null; }
		Date date = null;
		try {
			SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
			SimpleDateFormat format2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			SimpleDateFormat format3 = new SimpleDateFormat("yyyy-MM-dd HH:mm");
			if (sDate.length() == 10) {
				date = format1.parse(sDate);
			} else if (sDate.length() == 19) {
				date = format2.parse(sDate);
			} else if (sDate.length() == 16) {
				date = format3.parse(sDate);
			}
		} catch (ParseException e) {
			System.out.println("日期转型异常！");
			date = null;
		}
		return date;
	}
	
	/**
	 * string转Long型
	 * @param sNum
	 * @return
	 */
	public static Long stringToLong(String sNum) {
		if ("".equals(clearNull(sNum))) { return null; }
		Long lNum = null;
		try {
			lNum = Long.parseLong(sNum);
		} catch (Exception e) {
			// System.out.println("Long转型异常！");
		}
		return lNum;
	}
	
	/**
	 * 长整型转换为字符
	 * @param lon
	 * @return
	 */
	public static String longToString(Long lon) {
		String sDate = "";
		if (lon != null) {
			try {
				sDate = lon.toString();
			} catch (Exception e) {
				
			}
		}
		return sDate;
	}
	
	/**
	 * 长整型转换为浮点型
	 * @param lon
	 * @return
	 */
	public static long LongTolong(Long lon) {
		long lData = 0;
		if (lon != null) {
			try {
				lData = lon.longValue();
			} catch (Exception e) {
			}
		}
		return lData;
	}
	
	/**
	 * 字符型转换为整型
	 * @param num
	 * @return
	 */
	public static Integer stringToInteger(String num) {
		Integer iNum = 0;
		if (num != null || !"".equals(num)) {
			try {
				iNum = Integer.valueOf(num);
			} catch (Exception e) {
				iNum = 0;
			}
		}
		return iNum;
	}
	
	/**
	 * 获取时间
	 * @param format
	 * @return
	 */
	public static String getNowTime(String format) {
		SimpleDateFormat formatter = new SimpleDateFormat(format);
		java.util.Date now = new java.util.Date();
		String date = formatter.format(now);
		return date;
	}
	
	/**
	 * 过滤null
	 * @param s
	 * @return
	 */
	public static String clearNull(String s) {
		return (s == null || s.equals("null")) ? "" : s;
	}
	
	public static String clearNull(String s, String def) {
		if (s == null || "".equals(s.trim()) || s.trim().length() < 1) {
			return def;
		} else {
			return s;
		}
	}
	
	public static String clearNull(Object obj) {
		return (obj == null) ? "" : obj.toString();
	}
	
	public static String clearNull(Object s, String def) {
		if (s == null || "".equals(s.toString()) || s.toString().length() < 1) {
			return def;
		} else {
			return s.toString();
		}
	}
	
	/**
	 * 为编号填充0
	 * @param number
	 * @param digit
	 * @return
	 */
	public static String buildNumber(String number, int digit) {
		String tnum = "", tZero = "";
		int length = number.length();
		if (length <= 0 || length >= digit) { return number; }
		length = digit - length;
		for (int i = 0; i < length; i++) {
			tZero += "0";
		}
		tnum = tZero + number;
		return tnum;
	}
	
	/**
	 * 获取内部编号(时间16位+9位随机码)
	 */
	public static String getInnerNumber() {
		String sNum = "";
		try {
			Date now = new Date();
			SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmssMs");
			sNum = formatter.format(now);
			if (sNum.length() < 16) {
				for (int i = sNum.length(); i < 16; i++) {
					sNum += "0";
				}
			} else if (sNum.length() > 16) {
				sNum = sNum.substring(0, 16);
			}
			sNum += getRandomNumber(9);// 16+9
			sNum = (sNum.length() > 25) ? sNum.substring(0, 25) : sNum;// 内部编号小于25位
			// 如果循环插入时，间隔15毫秒就不会出现内部编号重复
			Thread.sleep(15);
			if (sNum.length() > 25) {
				sNum = sNum.substring(0, 25);
			}
		} catch (Exception e) {
		}
		return sNum;
	}
	
	/**
	 * 获取随机数
	 * @param length
	 * @return
	 */
	public static String getRandomNumber(int length) {
		String sStr = "";
		try {
			if (length < 1) { return sStr; }
			int iBeginNum = 1;// 从1开始
			long iEndNum = (long) Math.pow(10, length);
			long iRanNum = 0;
			iRanNum = (long) (Math.random() * (iEndNum - iBeginNum) + iBeginNum);
			sStr = String.valueOf(iRanNum);
			if (sStr.length() < length) {// 不够位数，就在左边补零
				sStr = buildNumber(sStr, length);
			} else if (sStr.length() > length) {
				sStr = sStr.substring(0, length);// 防止超出长度
			}
		} catch (Exception e) {
			e.printStackTrace();
			// 异常就用0来代替
			sStr = buildNumber("0", length);
		}
		return sStr;
	}
	
	/**
	 * 获取年龄
	 * @param idCard
	 *            身份证
	 * @param type
	 *            1：实龄 2：虚龄
	 * @return
	 */
	public static int getAgeByIdCard(String idCard, int type) {
		int age = 0;
		if (idCard == null || (idCard.length() != 15 && idCard.length() != 18)) { return 0; }
		try {
			String sYear = "", sMonth = "", sDay = "";
			if (idCard.length() == 18) {
				sYear = idCard.substring(6, 10);
				sMonth = idCard.substring(10, 12);
				sDay = idCard.substring(12, 14);
			} else if (idCard.length() == 15) {
				sYear = "19" + idCard.substring(6, 8);
				sMonth = idCard.substring(8, 10);
				sDay = idCard.substring(10, 12);
			}
			int iYear = 0, iMonth = 0, iDay = 0;
			if (!"".equals(sYear)) {
				iYear = Integer.parseInt(sYear);
			}
			if (!"".equals(sMonth)) {
				iMonth = Integer.parseInt(sMonth);
			}
			if (!"".equals(sDay)) {
				iDay = Integer.parseInt(sDay);
			}
			Calendar calendar = Calendar.getInstance();
			int nowYear = calendar.get(Calendar.YEAR);
			int nowMonth = calendar.get(Calendar.MONTH) + 1;
			int nowDay = calendar.get(Calendar.DAY_OF_MONTH);
			if (iYear != 0) {
				age = nowYear - iYear;
			}
			if (1 == type) {
				if (iMonth > nowMonth || (iMonth == nowMonth && iDay < nowDay)) {
					age -= 1;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			return 0;
		}
		return age;
	}
	
	/**
	 * 判断日期格式
	 * @param str
	 * @return
	 */
	public static boolean isDateFormat(String str) {
		if (str == null) { return false; }
		String sEx = "(([0-9]{3}[1-9]|[0-9]{2}[1-9][0-9]{1}|[0-9]{1}[1-9][0-9]{2}|[1-9][0-9]{3})-";
		sEx += "(((0[13578]|1[02])-(0[1-9]|[12][0-9]|3[01]))|((0[469]|11)-(0[1-9]|[12][0-9]|30))";
		sEx += "|(02-(0[1-9]|[1][0-9]|2[0-8]))))|((([0-9]{2})(0[48]|[2468][048]|[13579][26])|";
		sEx += "((0[48]|[2468][048]|[3579][26])00))-02-29)";
		if (str.length() == 10) {
			// Pattern code_p = Pattern.compile("\\d{4}\\-\\d{2}\\-\\d{2}");
			Pattern code_p = Pattern.compile(sEx);
			Matcher code_m = code_p.matcher(str);
			return code_m.find();
		} else if (str.length() == 4) {
			sEx = "([0-9]{3}[1-9]|[0-9]{2}[1-9][0-9]{1}|[0-9]{1}[1-9][0-9]{2}|[1-9][0-9]{3})";
			Pattern code_p = Pattern.compile(sEx);
			Matcher code_m = code_p.matcher(str);
			return code_m.find();
		} else {
			return false;
		}
	}
	
	/**
	 * 执行命令（使用cmd或者shell）
	 * @param sCommand
	 * @return
	 */
	public static String execCommand(String sCommand) {
		String sResult = "", sErrorResult = "";
		try {
			Runtime run = Runtime.getRuntime();
			Process process = run.exec(sCommand);
			BufferedReader input = new BufferedReader(new InputStreamReader(process.getInputStream()));
			BufferedReader error = new BufferedReader(new InputStreamReader(process.getErrorStream()));
			String line = null;
			while ((line = input.readLine()) != null) {
				sResult += line + "\n";
			}
			String errorLine = null;
			while ((errorLine = error.readLine()) != null) {
				sErrorResult += errorLine + "\n";
			}
			System.out.println("sCommand=" + sCommand);
			System.out.println("sResult=" + sResult);
			System.out.println("sErrorResult=" + sErrorResult);
			if (sErrorResult != null && sErrorResult.startsWith("ERROR")) {
				sResult = sErrorResult;
			}
			input.close();
			error.close();
		} catch (Exception e) {
			e.printStackTrace();
			sResult = "";
		}
		return sResult;
	}
	
	/**
	 * 检查数据值长度
	 * @param sStr:上传值
	 * @param sCheckType:检查类型【暂时支持M(max)、E(equal)、D(date)、N(No)】, 
	 * 					 格式(类型+长度,例如：M50代表最大长度为50位(必填)、E4代表长度为4位、
	 * 					 D10/D19/D16代表验证日期)、 N50代表最大长度为50位(可选)
	 * @param sMsgName:信息名称
	 * @param sErrorMsg:错误信息
	 * @return
	 */
	public static String checkData(String sStr, String sCheckType, String sMsgName, StringBuffer sErrorMsg) {
		sStr = clearNull(sStr);
		if ("".equals(sStr) && sCheckType.indexOf("N") == -1) {
			sErrorMsg.append("“" + sMsgName + "”为空；");
			return sStr;
		}
		try {
			int iLength = sStr.getBytes().length;
			// 把字符串分拆
			if (sCheckType == null || sCheckType.length() < 2) {
				sErrorMsg.append("检查“" + sMsgName + "”时“验证类型”为空；");
				return sStr;
			}
			String symbol = clearNull(sCheckType.substring(0, 1)).toUpperCase();
			int number = Integer.valueOf(sCheckType.substring(1, sCheckType.length()));
			// 判断检查类型
			if ("M".equals(symbol) || "N".equals(symbol)) {
				if (iLength > number) {
					sErrorMsg.append("“" + sMsgName + "”超过" + number + "位：" + sStr + "；");
					try {
						sStr = sStr.substring(0, number);
					} catch (StringIndexOutOfBoundsException e) {
						sStr = sStr.substring(0, number / 2);
					}
				}
			} else if ("E".equals(symbol)) {
				if (iLength > number) {
					sErrorMsg.append("“" + sMsgName + "”不等于" + number + "位：" + sStr + "；");
					try {
						sStr = sStr.substring(0, number);
					} catch (StringIndexOutOfBoundsException e) {
						sStr = sStr.substring(0, number / 2);
					}
				} else if (iLength < number) {
					sErrorMsg.append("“" + sMsgName + "”不等于" + number + "位：" + sStr + "；");
				}
			} else if ("D".equals(symbol)) {
				if (iLength > number) {
					sErrorMsg.append("“" + sMsgName + "”不等于" + number + "位：" + sStr + "；");
					try {
						sStr = sStr.substring(0, number);
					} catch (StringIndexOutOfBoundsException e) {
						sStr = sStr.substring(0, number / 2);
					}
					// sStr = this.dateToString(this.stringToDate(sStr));
				} else if (iLength < number) {
					sErrorMsg.append("“" + sMsgName + "”不等于" + number + "位：" + sStr + "；");
				} else if (isDateFormat(sStr) == false) {
					sErrorMsg.append("“" + sMsgName + "”格式有误：" + sStr + "；");
				}
			} else {
				sErrorMsg.append("检查“" + sMsgName + "”时“验证类型”有误，请与管理员联系；");
				return sStr;
			}
		} catch (Exception e) {
			sErrorMsg.append("检查“" + sMsgName + "”时“验证类型”有误，请与管理员联系；");
			e.printStackTrace();
		}
		return sStr;
	}
	
	
	/**
	 * string转Double型
	 * @param sNum
	 * @return
	 */
	public static Double stringToDouble(String sNum) {
		if ("".equals(clearNull(sNum))) { return 0d; }
		Double lNum = 0d;
		try {
			// lNum = Double.parseDouble(sNum);
			lNum = changeDouble(sNum, 2);
		} catch (Exception e) {
			// System.out.println("Double转型异常！");
		}
		return lNum;
	}
	
	/**
	 * string转Double型
	 * @param sNum
	 * @param precision
	 * @return
	 */
	public static Double stringToDouble(String sNum, int precision) {
		if ("".equals(clearNull(sNum))) { return null; }
		Double lNum = null;
		try {
			lNum = changeDouble(sNum, precision);
		} catch (Exception e) {
			// System.out.println("Double转型异常！");
		}
		return lNum;
	}
	
	/**
	 * 四舍五入函数，参数1：数值，参数2：要保留的小数位数
	 * @param sNum
	 * @param num
	 * @return
	 */
	public static Double changeDouble(String sNum, int num) {
		if (num < 0) return null;
		int k = 1;
		double tempNum = 0.0D;
		try {
			for (int i = 0; i < num; i++) {
				k = k * 10;
			}
			double a = Double.parseDouble(sNum);
			tempNum = (double) Math.round(a * k) / k;
		} catch (Exception e) {

		}
		return tempNum;
	}
	
	/**
	 * 浮点型转换为字符
	 * @param doub
	 * @return
	 */
	public static String doubleToString(Double doub) {
		String sDate = "0.00";
		if (doub != null) {
			try {
				// sDate = doub.toString();
				DecimalFormat format = new java.text.DecimalFormat("##0.00");
				sDate = format.format(doub);
			} catch (Exception e) {

			}
		}
		return sDate;
	}
	
	/**
	 * 整型转换为字符
	 * @param num
	 * @return
	 */
	public static String integerToString(Integer num) {
		String sNum = "0";
		if (num != null) {
			try {
				sNum = num.intValue() + "";
			} catch (Exception e) {

			}
		}
		return sNum;
	}
	
	/**
	 * 为编号填充0
	 * @param number
	 * @param digit
	 * @return
	 */
	public static String buildNumber(int number, int digit) {
		String tnum = "", tZero = "", tNumber = "";
		try {
			tNumber = String.valueOf(number);
		} catch (Exception e) {}
		int length = tNumber.length();
		if (length <= 0 || length >= digit) { return tNumber; }
		length = digit - length;
		for (int i = 0; i < length; i++) {
			tZero += "0";
		}
		tnum = tZero + number;
		return tnum;
	}
	
	/**
	 * 带“,”分隔的字符串转换成ArrayList
	 * @param str
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static ArrayList getHashStr(String str) {
		ArrayList allay = new ArrayList();
		String[] str2 = str.split(",");
		HashSet hs = new HashSet();
		for (int i = 0; i < str2.length; i++) {
			hs.add(str2[i]);
		}
		Iterator it = hs.iterator();
		while (it.hasNext()) {
			Object obj = (Object) it.next();
			allay.add(obj);
		}
		return allay;
	}
	
	public static void main(String[] args) throws Exception {
		// ChangeBean cb = new ChangeBean();
	}
}